package com.admin.business.venueProjectCommercialTenant;


import com.admin.business.venusProjectCommercialAuditRecord.VenusProjectCommercialAuditRecordDao;
import com.admin.business.venusProjectLifeServiceCost.VenusProjectLifeServiceCostDao;
import com.admin.business.voteEssentialInformation.VoteEssentialInformationDao;
import com.admin.utils.ImgImageBase64Util;
import com.admin.utils.PayUtil.WXPayUtil;
import com.admin.utils.PayUtility;
import com.admin.utils.RandomStrUtil;
import com.admin.utils.RedisUtilKey;
import com.tiangong.framework.annotation.OpenApi;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import com.zmbsms.os.core.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description: 商户表
 * @create: 2022-05-26 18:46:06
 **/
@Service("venueProjectCommercialTenant")
@Slf4j
public class VenueProjectCommercialTenantService {

    //审核记录dao
    @Resource
    VenusProjectCommercialAuditRecordDao venusProjectCommercialAuditRecordDao;

    //商户dao
    @Resource
    VenueProjectCommercialTenantDao venueProjectCommercialTenantDao;

    //订单dao
    @Resource
    VenusProjectLifeServiceCostDao venusProjectLifeServiceCostDao;

    @Autowired
    private RedisUtilKey redisTemplate;

    @Autowired
    private VoteEssentialInformationDao voteEssentialInformationDao;


    @OpenApi
    public Return testRedis(CDO cdoRequest) {
        String pro_name = cdoRequest.getString("pro_name");
        String code = cdoRequest.getString("code");
        redisTemplate.set(code, cdoRequest, 360L);
        Object redisCdo = redisTemplate.get(code);
        CDO cdo = CDO.copyToNewCDO(redisCdo);
        return Return.valueOf(cdo);
    }

    /**
     * 商户APP开通商户发起支付
     *
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return appOrderPayByOpenedBusinesses(CDO cdoRequest) {
        //判断redis里有没订单

        //判断cdo非空
        if (StringUtils.isEmpty(cdoRequest.getString("user_id"))) {
            return Return.valueOf(-2, "用户id不可为空");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_name"))) {
            return Return.valueOf(-2, "请填写商户名称");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_tel"))) {
            return Return.valueOf(-2, "请填写商户电话");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_type"))) {
            return Return.valueOf(-2, "请填写商户类型");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_province"))) {
            return Return.valueOf(-2, "请选择省");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_city"))) {
            return Return.valueOf(-2, "请选择市");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_area"))) {
            return Return.valueOf(-2, "请选择区");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_address_info"))) {
            return Return.valueOf(-2, "请填写商户详细地址");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_qualification_pic"))) {
            return Return.valueOf(-2, "请上传商户资质图片（多个用；分割）");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("order_money"))) {
            return Return.valueOf(-2, "认证金额不可为空");
        }
        //订单表字段
        //存入redis
        CDO redisCdo = new CDO();
        String code = this.rand("MO");//生成订单号
        redisCdo.set("commercial_name", cdoRequest.getString("commercial_name"));//商户名称
        redisCdo.set("user_id", cdoRequest.getString("user_id"));//支付人id
        redisCdo.set("cost_money", cdoRequest.getString("order_money"));//支付金额
        redisCdo.set("user_name", cdoRequest.getString("user_name"));//支付人姓名
        redisCdo.set("user_tel", cdoRequest.getString("user_tel"));//支付人电话
        redisCdo.set("cost_type", 1);//订单类型：1.商户认证 2.服务缴费
        redisCdo.set("cost_state", 0);//订单状态：0.待支付1.已下单2.已接单3.待评价4.待退款5.已完成
        redisCdo.set("pay_type", cdoRequest.getString("pay_type"));//支付方式0.微信1.支付宝
        redisCdo.set("cost_remark","商户号开通");//订单备注

        //商户表字段
        redisCdo.set("commercial_tel", cdoRequest.getString("user_tel"));//商户电话
        redisCdo.set("commercial_type", cdoRequest.getString("commercial_type"));//商户类型
        redisCdo.set("commercial_province", cdoRequest.getString("commercial_province"));//商户省
        redisCdo.set("commercial_city", cdoRequest.getString("commercial_city"));//商户市
        redisCdo.set("commercial_area", cdoRequest.getString("commercial_area"));//商户区/县
        redisCdo.set("commercial_address_info", cdoRequest.getString("commercial_address_info"));//商户详细地址
        redisCdo.set("commercial_pay", cdoRequest.getString("cost_money"));//商户支付金额
        redisCdo.set("create_user_id", cdoRequest.getString("create_user_id"));//商户创建人
        redisCdo.set("commercial_qualification_pic", cdoRequest.getString("commercial_qualification_pic"));//商户 资质图片（多个用；分割）
        redisCdo.set("commercial_audit_state", 0);//商家审核状态：0待支付、1待审核、2审核成功、3审核失败
        redisCdo.set("commercial_coordinate", cdoRequest.getString("commercial_coordinate"));//商家坐标
        redisCdo.set("commercial_image", cdoRequest.getString("commercial_image"));//商家门店图片



        //唤醒支付
        CDO wakePay = new CDO();
        wakePay.set("id", code);
        wakePay.set("sNotifyUrl", "https://admin.515f.com/tpapi/rest/v1/venueProjectCommercialTenant/rechargeCallbackByUsageFees");
        wakePay.set("attach", "生活服务");
        wakePay.set("body", "商户号开通");
        wakePay.set("orderVariable", 1);
        wakePay.set("orderDescription", "微信支付");
        wakePay.set("mweb", "APP");
        cdoRequest.set("orderMoney","0.01");
        wakePay.set("orderMoney", cdoRequest.getString("order_money"));
        Return paySign = PayUtility.getWXPaySign(wakePay);
        //存贮时间1小时
        redisTemplate.set(code, redisCdo, 3600L);
        return paySign;
    }


    /**
     * 商户app下单支付回调
     *
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return rechargeCallbackByUsageFees(CDO cdoRequest) {
        String strVersion = cdoRequest.getString("data");
        try {
            Map<String, String> mapResult = WXPayUtil.xmlToMap(strVersion);
            String trade_state = mapResult.get("return_code");
            if ("SUCCESS".equals(trade_state)) {
                //创建订单code
                Object redisCdo = redisTemplate.get(mapResult.get("out_trade_no"));
                CDO commercialInfo = CDO.copyToNewCDO(redisCdo);
                //添加商户号至venus_project_commercial_tenant
                    //更改商户审核状态
                commercialInfo.set("commercial_audit_state",1);
                venueProjectCommercialTenantDao.venueProjectCommercialTenantAdd(commercialInfo);
                //添加商户认证订单至venus_project_life_service_cost
                String commercial_id = commercialInfo.getString("commercial_id");
                commercialInfo.set("commercial_id",commercial_id);
                commercialInfo.set("cost_state", 1);
                venusProjectLifeServiceCostDao.addLifeServiceCostRecord(commercialInfo);
            }else {
                return Return.valueOf(-1,"订单处理异常！");
            }
        } catch (Exception e) {
            return Return.valueOf(-1, "---------微信支付回调地址处理异常:{}----------");
        }
        return Return.SUCCESS;
    }


    /**
     * 生成订单号
     *
     * @param src
     * @return
     */
    public String rand(String src) {
        Date currTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String time = formatter.format(currTime);
        String timeMillis = currTime.getTime() + "";
        String item = timeMillis.substring(timeMillis.length() - 4);//时间戳后四位
        String codeItem = RandomStrUtil.getRandInt(3);//随机码四位
        String rand = src + time + item + codeItem;
        return rand;
    }


    /**
     * @return 校验新增商户是否重复
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return addVenueProjectCommercialTenant(CDO cdoRequest) {
        CDO cdoResult = new CDO();
        //校验是否存在相同名称
        CDO result = venueProjectCommercialTenantDao.getVenueProjectCommercialTenant(cdoRequest);
        if (result != null) {
            cdoResult.set("success", false);
            cdoResult.set("msg", "该商户已存在！");
            return Return.valueOf(cdoResult);
        }

        cdoRequest.set("create_time", new Date());
        venueProjectCommercialTenantDao.venueProjectCommercialTenantAdd(cdoRequest);

        return Return.valueOf(cdoRequest);
    }

    /**
     * @return 根据商家名字回显商家认证信息
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenueProjectCommercialTenant(CDO cdoRequest) {
        CDO result = venueProjectCommercialTenantDao.getVenueProjectCommercialTenant(cdoRequest);
        CDO cdoResult = new CDO();
        cdoResult.set("data", result);
        return Return.valueOf(result);
    }

    /**
     * @return 支付成功后调用此接口
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return updateVenueProjectCommercialTenant(CDO cdoRequest) {
        venueProjectCommercialTenantDao.updateVenueProjectCommercialTenant(cdoRequest);
        return Return.valueOf(cdoRequest);
    }

    /**
     * @return 商户列表
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenusProjectCommercialTenantPageFaoShangHu(CDO cdoRequest) {
        Integer pageIndex = cdoRequest.containsKey("pageIndex") ? cdoRequest.getInteger("pageIndex") : 0;
        int recordSize = cdoRequest.containsKey("recordSize") ? cdoRequest.getInteger("recordSize") : 10;
        cdoRequest.set("recordFrom", pageIndex * recordSize);
        cdoRequest.set("recordSize", recordSize);
        List<CDO> cdoMapperResultList = venueProjectCommercialTenantDao.getVenusProjectCommercialTenantPageFaoShangHu(cdoRequest);
        boolean isEndPage = false;
        if (cdoMapperResultList.size() < recordSize) {
            isEndPage = true;
        }
        CDO cdoResult = new CDO();
        cdoResult.set("isEndPage", isEndPage);
        cdoResult.set("datalist", cdoMapperResultList);
        Integer total = venueProjectCommercialTenantDao.selectVenusProjectCommercialTenantPageShangHuCount(cdoRequest);
        cdoResult.set("total", total);
        return Return.valueOf(cdoResult);
    }

    /**
     * @return 商家认证审批分页
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenusProjectCommercialTenantPage(CDO cdoRequest) {

        Integer pageIndex = cdoRequest.containsKey("pageIndex") ? cdoRequest.getInteger("pageIndex") : 0;
        int recordSize = cdoRequest.containsKey("recordSize") ? cdoRequest.getInteger("recordSize") : 10;
        cdoRequest.set("recordFrom", pageIndex * recordSize);
        cdoRequest.set("recordSize", recordSize);
        List<CDO> cdoMapperResultList = venueProjectCommercialTenantDao.getVenusProjectCommercialTenant(cdoRequest);
        boolean isEndPage = false;
        if (cdoMapperResultList.size() < recordSize) {
            isEndPage = true;
        }
        CDO cdoResult = new CDO();
        cdoResult.set("isEndPage", isEndPage);
        cdoResult.set("datalist", cdoMapperResultList);

        Integer total = venueProjectCommercialTenantDao.selectVenusProjectCommercialTenantCount(cdoRequest);
        cdoResult.set("total", total);
        return Return.valueOf(cdoResult);
    }

    /**
     * @return 审批查询
     * 商家认证审批详情
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return getVenueProjectCommercialTenantById(CDO cdoRequest) {
        CDO result = venueProjectCommercialTenantDao.getVenueProjectCommercialTenantById(cdoRequest);
        Integer create_user_id = Integer.valueOf(result.getString("create_user_id"));
        CDO sysUser = venueProjectCommercialTenantDao.getSysUserById(create_user_id.longValue());
        //获取注册人姓名
        String user_name = sysUser.getString("user_name");
        //获取注册人电话
        String user_tel = sysUser.getString("user_tel");
        //获取注册人身份证
        String user_card_code = sysUser.getString("user_card_code");
        CDO cdoResult = new CDO();
        cdoResult.set("data", result);
        if (null != user_name) {
            result.set("user_name", user_name);
        } else {
            return Return.valueOf(-1, "未获取到用户姓名！", false);
        }
        if (null != user_tel) {
            result.set("user_tel", user_tel);
        } else {
            return Return.valueOf(-1, "未获取到用户手机号！", false);
        }
        if (null != user_card_code) {
            result.set("user_card_code", user_card_code);
        } else {
            return Return.valueOf(-1, "未获取到用户身份证信息！", false);
        }
        return Return.valueOf(result);
    }

    /**
     * @return 审核（驳回或者通过）
     * @author whs
     * @create: 2022-05-26
     */
    @OpenApi
    public Return updateVenueProjectCommercialTenantState(CDO cdoRequest) {
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_id"))){
            return Return.valueOf(-1,"商户id不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_audit_state"))){
            return Return.valueOf(-1,"审批状态不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_audit_user_id"))){
            return Return.valueOf(-1,"审批人id不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("audit_user_name"))){
            return Return.valueOf(-1,"审批人姓名不能为空！");
        }
        if (StringUtils.isEmpty(cdoRequest.getString("commercial_audit_opinion"))){
            return Return.valueOf(-1,"审批意见不能为空！");
        }
        //审批成功
        if (cdoRequest.getString("commercial_audit_state").equals(2)){
            cdoRequest.set("commercial_audit_state",2);//商家审核状态：0待支付、1待审核、2审核成功、3审核失败
            cdoRequest.set("commercial_state",0);//商家状态:0.正常1.下架
            venueProjectCommercialTenantDao.updateVenueProjectCommercialTenantState(cdoRequest);
            //审批人id
            cdoRequest.set("audit_user_id",cdoRequest.getString("commercial_audit_user_id"));
            cdoRequest.set("audit_result",0);//审核结果0审核成功、1审核失败
            //审核意见
            cdoRequest.set("audit_opinion",cdoRequest.getString("commercial_audit_opinion"));
            cdoRequest.set("audit_type",0);//审核类型0.商家认证1.商家服务上架
            venusProjectCommercialAuditRecordDao.insertVenusProjectCommercialAuditRecord(cdoRequest);
            return Return.valueOf(200,"审核成功！");

        }else {//审批失败
            cdoRequest.set("commercial_audit_state",3);//商家审核状态：0待支付、1待审核、2审核成功、3审核失败
            venueProjectCommercialTenantDao.updateVenueProjectCommercialTenantState(cdoRequest);
            //审批人id
            cdoRequest.set("audit_user_id",cdoRequest.getString("commercial_audit_user_id"));
            //审核人姓名
            cdoRequest.set("audit_user_name",cdoRequest.get("commercial_audit_user_name"));
            cdoRequest.set("audit_result",1);//审核结果0审核成功、1审核失败
            //审核意见
            cdoRequest.set("audit_opinion",cdoRequest.getString("commercial_audit_opinion"));
            cdoRequest.set("audit_type",0);//审核类型0.商家认证1.商家服务上架
            venusProjectCommercialAuditRecordDao.insertVenusProjectCommercialAuditRecord(cdoRequest);
            return Return.valueOf(200,"审核失败！");
        }
    }

    /**
     * @return 根据商户id找到该商户所有服务
     * @author zir
     */
    @OpenApi
    public Return getAllServicePageByCommercialId(CDO cdoRequest) {
        //分页参数
        Integer pageIndex = cdoRequest.containsKey("pageIndex") ? cdoRequest.getInteger("pageIndex") : 0;
        int recordSize = cdoRequest.containsKey("recordSize") ? cdoRequest.getInteger("recordSize") : 10;
        cdoRequest.set("recordFrom", pageIndex * recordSize);
        cdoRequest.set("recordSize", recordSize);

        List<CDO> serviceList = venueProjectCommercialTenantDao.selectAllServiceByCommercialId(cdoRequest);
        CDO result = new CDO();
        result.set("data", serviceList);


        Integer total = venueProjectCommercialTenantDao.selectAllServiceByCommercialIdCount(cdoRequest);
        result.set("total", total);
        return Return.valueOf(result);
    }

    /**
     * 获取商家服务类型列表
     *
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return getCommercialTenantServerTypeList(CDO cdoRequest) {
        List<CDO> resultList = venueProjectCommercialTenantDao.selectCommercialTenantServerTypeList();
        CDO result = new CDO();
        result.set("data", resultList);
        return Return.valueOf(result);
    }

    /**
     * 通过ID批量下架商家
     */
    @OpenApi
    public Return RemoveCommercialTenantByIds(CDO cdoRequest){
        String data = cdoRequest.getString("data");
        String[] ids = data.split(",");
        for (String sid:ids){
            int id = Integer.parseInt(sid);
            venueProjectCommercialTenantDao.updateCommercialTenantByIds(id);
        }
        return Return.valueOf(cdoRequest);
    }

    /**
     * 获取该商家所有认证记录
     */
    @OpenApi
    public Return getCommercialTenantAllAudit(CDO cdoRequest){
        List<CDO> auditList = venueProjectCommercialTenantDao.selectVenusProjectCommercialAllAuditByCommercialIdAndAuditId(cdoRequest);
        CDO cdoResult = new CDO();
        cdoResult.set("data",auditList);
        return Return.valueOf(cdoResult);
    }

    /**
     * 商家认证--省市县三级联动
     * @return
     */
    @OpenApi
    public Return getProvinceCityCountyList(CDO cdoRequest){
        List<CDO> provinceCityCountyList = venueProjectCommercialTenantDao.selectProvinceCityCountyList();
        List<CDO> result = initList("1", provinceCityCountyList);
        return Return.valueOf(result);
    }

    /**
     * 内部方法-迭代器
     * @param pId
     * @param provinceCityCountyList
     * @return
     */
    private List<CDO> initList(String pId, List<CDO> provinceCityCountyList) {
        ArrayList<CDO> result = new ArrayList<>();
        for (CDO cdo:provinceCityCountyList){
            if(pId.equals(cdo.getString("parent_id"))){
                cdo.set("childList",initList(cdo.getString("id"),provinceCityCountyList));
                result.add(cdo);
            }
        }
        return result;
    }
    /**
     * 商家认证上传资质
     */
    @OpenApi
    public Return uploadImageUrl(CDO cdoRequest){
        try {
            String imageBase64 = cdoRequest.getString("imageBase64");
            if (StringUtils.isEmpty(imageBase64)){
                return Return.valueOf(-1,"上传资质不能为空！");
            }
            return Return.valueOf(200,"上传成功！", ImgImageBase64Util.uploadImgBase64(imageBase64));
        }catch (Exception e){
            return Return.valueOf(-1,"上传失败！");
        }
    }

    /**
     * 获取商家认证费用
     * @param cdoRequest
     * @return
     */
    @OpenApi
    public Return getCommercialSetOrderMoney(CDO cdoRequest){
        CDO cdo = venueProjectCommercialTenantDao.selectCommercialSetOrderMoney();
        if (cdo.getString("expense").isEmpty()){
            return Return.valueOf(-1,"查询认证费用失败！");
        }
        return Return.valueOf(cdo);
    }
}
